<template>
	<u-popup safe-area-inset-bottom border-radius="25" closeable mode="bottom" v-model="show">
		<view class="container">
			<view class="title">{{title}}</view>
			<view class="handCenter" :style="getStyle">
				<canvas class="hand-writing" disable-scroll @touchstart="uploadScaleStart" @touchmove="uploadScaleMove"
					@touchend="uploadScaleEnd" :canvas-id="canvasId" ref="canvas"></canvas>
			</view>
			<view class="buttons">
				<u-button @click="rewrite" type="default">重签</u-button>
				<u-button @click="onSubmit" type="primary">提交</u-button>
			</view>
		</view>
		<u-toast ref="uToast" />
	</u-popup>
</template>

<script>
	import Handwriting from './signature.js';
	import UPNG from 'upng-js';

	export default {
		emits: ['change', 'input'],
		props: {
			visible: {
				type: Boolean,
				requried: false,
				default: false
			},
			value: {
				type: String,
				requried: false
			},
			title: {
				type: String,
				requried: false,
				default: '手写签名'
			},
			height: {
				type: [String, Number],
				requried: false,
				default: '300rpx'
			},
			backgroundColor: {
				type: String,
				required: false
			},
			penColor: {
				type: String,
				default: '#000',
				required: false
			},
			/**
			 * 自动剪切到签字内容的边界（没有背景色的情况下）
			 */
			autoTrim: {
				type: Boolean,
				default: false,
				required: false
			},
		},
		data() {
			return {
				canvasId: '__signature__canvas',
				width: '100%',
				signature: null,
			};
		},
		computed: {
			getStyle() {
				return {
					width: this.width,
					height: this.height
				}
			},
			show: {
				get() {
					return this.visible;
				},
				set(val) {
					if (!val) {
						this.$emit('close');
					}
				}
			}
		},
		watch: {
			visible(val) {
				if (val) {
					this.sign();
				}
			},
			value(newVal, oldVal) {
				if (newVal != oldVal) {
					if (newVal) {
						this.signature = JSON.parse(newVal);
					} else {
						this.signature = null;
					}
					this.sign();
				}
			}
		},
		mounted() {
			//this.sign();
		},
		methods: {
			resizeCanvas(ctx, width, height) {
				// #ifdef APP
				// 获取设备信息
				const systemInfo = uni.getSystemInfoSync();
				// 设备像素比（等效于 window.devicePixelRatio）
				const devicePixelRatio = systemInfo.pixelRatio;
				// #endif
				// #ifndef APP
				const devicePixelRatio = window.devicePixelRatio;
				// #endif
				console.log('width', width, width * devicePixelRatio, 'height', height, height * devicePixelRatio)
				//console.log('设备像素比:', devicePixelRatio);
				this.$refs.canvas.width = width * devicePixelRatio;
				this.$refs.canvas.height = height * devicePixelRatio;
				//ctx.scale(devicePixelRatio, devicePixelRatio);
				ctx.setTransform(devicePixelRatio, 0, 0, devicePixelRatio, 0, 0)
			},
			sign() {
				if (!this.visible) return;
				this.$nextTick(() => {
					let query = uni.createSelectorQuery().in(this);
					let ctx = uni.createCanvasContext(this.canvasId, this);

					this.handwriting = new Handwriting({
						penColor: this.penColor,
						slideValue: 50, // 0, 25, 50, 75, 100
						canvasName: this.canvasId,
						ctx: ctx
					});

					query
						.select('.handCenter')
						.boundingClientRect(rect => {
							this.handwriting.setSize(rect);
							//this.resizeCanvas(ctx, rect.width, rect.height);
							// 如果设置了背景色，在这里初始化画布背景
							if (this.backgroundColor) {
								ctx.setFillStyle(this.backgroundColor);
								ctx.fillRect(0, 0, rect.width, rect.height);
								ctx.draw();
							}
							if (this.signature) {
								const bound = this.signature.bound || {
									left: 0,
									right: rect.width,
									top: 0,
									bottom: rect.height
								};
								this.handwriting.fromDataURL(this.signature.imgUrl, {
									xOffset: bound.left,
									yOffset: bound.top,
									width: bound.right - bound.left - 4.5,
									height: bound.bottom - bound.top - 4
								});
							}
						})
						.exec();
				});
			},
			rewrite() {
				this.handwriting.clear();
			},
			onSubmit() {
				if (this.handwriting.isEmpty()) {
					// 未签字
					return this.$refs.uToast.show({
						title: '请在框内签字',
						type: 'error'
					});
				}
				this.toDataUrl();
			},
			uploadScaleStart(event) {
				this.handwriting.uploadScaleStart(event);
			},
			uploadScaleMove(event) {
				this.handwriting.uploadScaleMove(event);
			},
			uploadScaleEnd(event) {
				this.handwriting.uploadScaleEnd(event);
			},
			convertToBase64() {
				const left = this.autoTrim ? Math.max(this.handwriting.cutArea.left - 2.5, 0) : 0;
				const top = this.autoTrim ? Math.max(this.handwriting.cutArea.top - 2, 0) : 0;
				const right = this.autoTrim ? Math.min(this.handwriting.cutArea.right + 2, this.handwriting.canvasWidth) :
					this.handwriting.canvasWidth;
				const bottom = this.autoTrim ? Math.min(this.handwriting.cutArea.bottom + 2, this.handwriting
					.canvasHeight) : this.handwriting.canvasHeight;
				uni.canvasGetImageData({
					canvasId: this.canvasId,
					x: left,
					y: top,
					width: right - left,
					height: bottom - top,
					success: (res) => {
						let croppedData = res;

						if (croppedData) {
							// 使用 UPNG.js 编码为 PNG
							const pngBuffer = UPNG.encode([croppedData.data.buffer], croppedData.width,
								croppedData.height, 0);
							// 将 ArrayBuffer 转为 Base64
							const base64 = uni.arrayBufferToBase64(pngBuffer);
							const dataURL = `data:image/png;base64,${base64}`;
							const res = {
								data: dataURL,
								bound: {
									left,
									top,
									right,
									bottom
								}
							}
							this.$emit('input', JSON.stringify(res));
							this.$emit('change', res);
						}
					}
				}, this);
			},
			toDataUrl() {
				return this.convertToBase64();
			}
		}
	};
</script>

<style scoped>
	.container {
		width: 100%;
		/* height: 822rpx; */
		position: relative;
		background-color: #fff;
	}

	.title {
		width: 100%;
		display: flex;
		justify-content: center;
		color: #3e3e3e;
		font-size: 38rpx;
		font-weight: bold;
		margin-top: 35rpx;
	}

	.handCenter {
		margin: 35rpx auto 0;
		border: 1px dashed #979797;
	}

	.hand-writing {
		width: 100%;
		height: 100%;
	}

	.buttons {
		width: 570rpx;
		margin: 40rpx auto;
		display: flex;
		justify-content: space-between;
	}

	.buttons .button {
		width: 200rpx;
		height: 78rpx;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 14rpx;
		font-size: 33rpx;
	}

	.buttons .button.button_rewrite {
		border: 1px solid #ff3b3b;
		background-color: #ffffff;
		color: #ff4343;
	}

	.buttons .button.button_submit {
		background-color: #ff824e;
		color: #fff;
	}
</style>